# -*- coding: UTF-8 -*-

# 引入 Matplotlib 的分模块 pyplot
import matplotlib.pyplot as plt
# 引入 numpy
import numpy as np

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['FangSong']

plt.xlabel("含水量 %", loc='right')
plt.ylabel('干\n密\n度\n g/$\mathregular{cm^3}$', rotation=0)
plt.title('击实试验')


x = [13.4, 15.6, 17.6, 19.4, 21.4]
y = [1.647, 1.690, 1.708, 1.642, 1.559]

# 拟合
z1 = np.polyfit(x, y, deg=2)
# 得到多项式系数，按照阶数从高到低排列
func = np.poly1d(z1)
# 显示多项式
print(func)

x2 = np.linspace(13, 22, 100)
y_predict = func(x2)

max_y, min_y = max(y_predict), min(y_predict)
max_index = np.where(y_predict == np.max(y_predict))
max_x, min_x = max(x2[max_index]), min(x2)

y_label = '最大干密度: ' + str(round(max_y, 3)) + ' g/$\mathregular{cm^3}$'
x_label = '最佳含水量: ' + str(round(max_x, 2)) + ' %'
# 垂直坐标辅助线
plt.hlines(max_y, xmin=min_x, xmax=max_x, ls='dashdot', colors='gray', label=y_label)
plt.vlines(max_x, ymin=min_y, ymax=max_y, ls='dotted', colors='gray', label=x_label)

plt.scatter(x, func(x))
plt.plot(x2, y_predict, 'r')

# 网格线
plt.grid()
# 图例
plt.legend(loc='upper right')
# 显示图像
plt.show()
